package com.sinothk.file.preview.demo

import android.app.AlertDialog
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.tencent.smtt.export.external.interfaces.IX5WebChromeClient
import com.tencent.smtt.export.external.interfaces.JsResult
import com.tencent.smtt.sdk.*
import com.tencent.smtt.utils.TbsLog
import kotlinx.android.synthetic.main.activity_tbs_demo_main.*


class TbsDemoWebViewMainActivity : AppCompatActivity() {
    private val TAG = "TbsDemoMainActivity"
    //    private var mViewParent: FrameLayout? = null
    private var mWebView: WebView? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_tbs_web_view_demo_main)

        mWebView = WebView(this, null)
        mViewParent!!.addView(
            mWebView, FrameLayout.LayoutParams(
                FrameLayout.LayoutParams.FILL_PARENT,
                FrameLayout.LayoutParams.FILL_PARENT
            )
        )

        init()
//        mWebView!!.loadUrl()
    }

    private fun init() {
        mWebView = WebView(this, null)
        mViewParent.addView(
            mWebView, FrameLayout.LayoutParams(
                FrameLayout.LayoutParams.FILL_PARENT,
                FrameLayout.LayoutParams.FILL_PARENT
            )
        )
//        initProgressBar()
        mWebView!!.webViewClient = object : WebViewClient() {
            override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
                return false
            }

            override fun onPageFinished(view: WebView, url: String) {
                super.onPageFinished(view, url)
                // mTestHandler.sendEmptyMessage(MSG_OPEN_TEST_URL);
//                mTestHandler.sendEmptyMessageDelayed(BrowserActivity.MSG_OPEN_TEST_URL, 5000) // 5s?
//                if (Build.VERSION.SDK.toInt() >= 16) changGoForwardButton(view)
                /* mWebView.showLog("test Log"); */
            }
        }
        mWebView!!.webChromeClient = object : WebChromeClient() {
            override fun onJsConfirm(
                arg0: WebView, arg1: String, arg2: String,
                arg3: JsResult
            ): Boolean {
                return super.onJsConfirm(arg0, arg1, arg2, arg3)
            }

            var myVideoView: View? = null
            var myNormalView: View? = null
            var callback: IX5WebChromeClient.CustomViewCallback? = null
            // /////////////////////////////////////////////////////////
            //
            /**
             * 全屏播放配置
             */
            override fun onShowCustomView(
                view: View,
                customViewCallback: IX5WebChromeClient.CustomViewCallback
            ) { //				FrameLayout normalView = (FrameLayout) findViewById(R.id.web_filechooser);
                //				ViewGroup viewGroup = (ViewGroup) normalView.getParent();
                //				viewGroup.removeView(normalView);
                //				viewGroup.addView(view);
                //				myVideoView = view;
                //				myNormalView = normalView;
                //				callback = customViewCallback;
            }

            override fun onHideCustomView() {
                if (callback != null) {
                    callback!!.onCustomViewHidden()
                    callback = null
                }
                if (myVideoView != null) {
                    val viewGroup = myVideoView!!.parent as ViewGroup
                    viewGroup.removeView(myVideoView)
                    viewGroup.addView(myNormalView)
                }
            }

            override fun onJsAlert(
                arg0: WebView, arg1: String, arg2: String,
                arg3: JsResult
            ): Boolean {
                /**
                 * 这里写入你自定义的window alert
                 */
                return super.onJsAlert(null, arg1, arg2, arg3)
            }
        }
        mWebView!!.setDownloadListener { arg0, arg1, arg2, arg3, arg4 ->
            TbsLog.d(TAG, "url: $arg0")
            AlertDialog.Builder(this@TbsDemoWebViewMainActivity)
                .setTitle("allow to download？")
                .setPositiveButton(
                    "yes"
                ) { dialog, which ->
                    Toast.makeText(
                        this@TbsDemoWebViewMainActivity,
                        "fake message: i'll download...",
                        1000
                    ).show()
                }
                .setNegativeButton(
                    "no"
                ) { dialog, which ->
                    Toast.makeText(
                        this@TbsDemoWebViewMainActivity,
                        "fake message: refuse download...",
                        Toast.LENGTH_SHORT
                    ).show()
                }
                .setOnCancelListener {
                    Toast.makeText(
                        this@TbsDemoWebViewMainActivity,
                        "fake message: refuse download...",
                        Toast.LENGTH_SHORT
                    ).show()
                }.show()
        }
        val webSetting = mWebView!!.settings
        webSetting.allowFileAccess = true
        webSetting.layoutAlgorithm = WebSettings.LayoutAlgorithm.NARROW_COLUMNS
        webSetting.setSupportZoom(true)
        webSetting.builtInZoomControls = true
        webSetting.useWideViewPort = true
        webSetting.setSupportMultipleWindows(false)
        // webSetting.setLoadWithOverviewMode(true);
        webSetting.setAppCacheEnabled(true)
        // webSetting.setDatabaseEnabled(true);
        webSetting.domStorageEnabled = true
        webSetting.javaScriptEnabled = true
        webSetting.setGeolocationEnabled(true)
        webSetting.setAppCacheMaxSize(Long.MAX_VALUE)
        webSetting.setAppCachePath(getDir("appcache", 0).path)
        webSetting.databasePath = getDir("databases", 0).path
        webSetting.setGeolocationDatabasePath(
            getDir("geolocation", 0)
                .path
        )
        // webSetting.setPageCacheCapacity(IX5WebSettings.DEFAULT_CACHE_CAPACITY);
        webSetting.pluginState = WebSettings.PluginState.ON_DEMAND
        // webSetting.setRenderPriority(WebSettings.RenderPriority.HIGH);
// webSetting.setPreFectch(true);
        val time = System.currentTimeMillis()
//        if (mIntentUrl == null) {
            mWebView!!.loadUrl("http://view.xdocin.com/doc/preview.docx")
//        } else {
//            mWebView!!.loadUrl(mIntentUrl.toString())
//        }
        TbsLog.d(
            "time-cost", "cost time: "
                    + (System.currentTimeMillis() - time)
        )
        CookieSyncManager.createInstance(this)
        CookieSyncManager.getInstance().sync()
    }
}
